// src/adapters/huawei_cloud_adapter.rs

use crate::interfaces::{
    DataSourceAdapter, DataSourceConnection, ConnectionStatus, DataSourceSchema,
    SchemaExtractionResult, DataQuery, QueryResult, TestResult,
};
use crate::config::HuaweiCloudConfig;
use crate::models::{DataSourceType, FieldDefinition, Relationship, Constraint};
use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use anyhow::{anyhow, Result as AnyhowResult};
use log::{debug, info, warn, error};

/// 华为云物联网平台适配器
/// 支持华为云IoTDA API的完整集成
pub struct HuaweiCloudAdapter {
    /// HTTP客户端
    client: Client,
    /// 配置
    config: HuaweiCloudConfig,
    /// 连接状态
    connection_status: tokio::sync::RwLock<ConnectionStatus>,
    /// 缓存管理
    cache: HuaweiCloudCache,
    /// API限流器
    rate_limiter: RateLimiter,
}

/// 华为云IoTDA API响应结构
#[derive(Debug, Deserialize, Serialize)]
pub struct HuaweiCloudResponse<T> {
    /// 响应码
    pub code: i32,
    /// 响应消息
    pub message: String,
    /// 响应数据
    pub data: Option<T>,
}

/// 设备信息
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceInfo {
    /// 设备ID
    pub device_id: String,
    /// 设备名称
    pub device_name: String,
    /// 产品ID
    pub product_id: String,
    /// 节点类型
    pub node_type: String,
    /// 设备状态
    pub status: String,
    /// 创建时间
    pub created_time: String,
    /// 最后在线时间
    pub last_online_time: String,
    /// 标签
    pub tags: Option<Vec<DeviceTag>>,
}

/// 设备标签
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceTag {
    /// 标签键
    pub tag_key: String,
    /// 标签值
    pub tag_value: String,
}

/// 产品信息
#[derive(Debug, Deserialize, Serialize)]
pub struct ProductInfo {
    /// 产品ID
    pub product_id: String,
    /// 产品名称
    pub product_name: String,
    /// 设备类型
    pub device_type: String,
    /// 协议类型
    pub protocol_type: String,
    /// 数据格式
    pub data_format: String,
    /// 创建时间
    pub created_time: String,
}

/// 设备属性
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceProperties {
    /// 服务ID
    pub service_id: String,
    /// 属性列表
    pub properties: Vec<DeviceProperty>,
}

/// 设备属性项
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceProperty {
    /// 属性名称
    pub property_name: String,
    /// 数据类型
    pub data_type: String,
    /// 读写权限
    pub access: String,
    /// 描述
    pub description: Option<String>,
    /// 取值范围
    pub enum_list: Option<Vec<String>>,
    /// 最小值
    pub min: Option<f64>,
    /// 最大值
    pub max: Option<f64>,
    /// 步长
    pub step: Option<f64>,
    /// 单位
    pub unit: Option<String>,
}

/// 设备命令
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceCommand {
    /// 命令ID
    pub command_id: String,
    /// 服务ID
    pub service_id: String,
    /// 命令名称
    pub command_name: String,
    /// 参数列表
    pub paras: Vec<CommandParameter>,
}

/// 命令参数
#[derive(Debug, Deserialize, Serialize)]
pub struct CommandParameter {
    /// 参数名称
    pub para_name: String,
    /// 数据类型
    pub data_type: String,
    /// 是否必选
    pub required: bool,
    /// 描述
    pub description: Option<String>,
    /// 取值范围
    pub enum_list: Option<Vec<String>>,
    /// 最小值
    pub min: Option<f64>,
    /// 最大值
    pub max: Option<f64>,
    /// 步长
    pub step: Option<f64>,
    /// 单位
    pub unit: Option<String>,
}

/// 设备事件
#[derive(Debug, Deserialize, Serialize)]
pub struct DeviceEvent {
    /// 事件类型
    pub event_type: String,
    /// 服务ID
    pub service_id: String,
    /// 事件名称
    pub event_name: String,
    /// 参数列表
    pub paras: Vec<EventParameter>,
}

/// 事件参数
#[derive(Debug, Deserialize, Serialize)]
pub struct EventParameter {
    /// 参数名称
    pub para_name: String,
    /// 数据类型: String,
    /// 描述
    pub description: Option<String>,
    /// 取值范围
    pub enum_list: Option<Vec<String>>,
    /// 最小值
    pub min: Option<f64>,
    /// 最大值
    pub max: Option<f64>,
    /// 步长
    pub step: Option<f64>,
    /// 单位
    pub unit: Option<String>,
}

/// 华为云缓存管理
pub struct HuaweiCloudCache {
    /// 设备信息缓存
    device_cache: tokio::sync::RwLock<HashMap<String, CachedDeviceInfo>>,
    /// 产品信息缓存
    product_cache: tokio::sync::RwLock<HashMap<String, CachedProductInfo>>,
    /// 缓存配置
    cache_ttl: Duration,
}

/// 缓存的设备信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedDeviceInfo {
    /// 设备信息
    pub device_info: DeviceInfo,
    /// 缓存时间
    pub cached_at: Instant,
    /// 过期时间
    pub expires_at: Instant,
}

/// 缓存的产品信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedProductInfo {
    /// 产品信息
    pub product_info: ProductInfo,
    /// 缓存时间
    pub cached_at: Instant,
    /// 过期时间
    pub expires_at: Instant,
}

/// API限流器
pub struct RateLimiter {
    /// 请求计数器
    request_count: tokio::sync::RwLock<u32>,
    /// 时间窗口开始时间
    window_start: tokio::sync::RwLock<Instant>,
    /// 最大请求数
    max_requests: u32,
    /// 时间窗口
    time_window: Duration,
}

impl HuaweiCloudAdapter {
    /// 创建新的华为云适配器
    pub fn new(config: HuaweiCloudConfig) -> AnyhowResult<Self> {
        let client = Client::builder()
            .timeout(Duration::from_secs(config.timeout_secs))
            .user_agent("IndustryAgent/1.0")
            .build()?;

        Ok(Self {
            client,
            config,
            connection_status: tokio::sync::RwLock::new(ConnectionStatus::Disconnected),
            cache: HuaweiCloudCache::new(),
            rate_limiter: RateLimiter::new(),
        })
    }

    /// 构建API请求URL
    fn build_api_url(&self, endpoint: &str) -> String {
        format!("{}/v5/iot/{}/{}",
            self.config.base_url.trim_end_matches('/'),
            self.config.project_id,
            endpoint.trim_start_matches('/')
        )
    }

    /// 添加认证头
    fn add_auth_headers(&self, headers: reqwest::HeaderMap) -> AnyhowResult<reqwest::HeaderMap> {
        let mut headers = headers;

        // 添加认证Token
        headers.insert(
            reqwest::header::AUTHORIZATION,
            format!("Bearer {}", self.config.access_token).parse()?
        );

        // 添加内容类型
        headers.insert(
            reqwest::header::CONTENT_TYPE,
            "application/json".parse()?
        );

        Ok(headers)
    }

    /// 检查并等待限流
    async fn check_rate_limit(&self) -> AnyhowResult<()> {
        self.rate_limiter.acquire().await
    }

    /// 执行API请求
    async fn execute_request<T: for<'de> Deserialize<'de>>(
        &self,
        method: reqwest::Method,
        url: &str,
        body: Option<serde_json::Value>,
    ) -> AnyhowResult<T> {
        // 检查限流
        self.check_rate_limit().await?;

        let mut request = self.client.request(method, url);

        // 添加认证头
        let headers = self.add_auth_headers(reqwest::header::HeaderMap::new())?;
        request = request.headers(headers);

        // 添加请求体
        if let Some(body) = body {
            request = request.json(&body);
        }

        // 发送请求
        let response = request.send().await?;

        if !response.status().is_success() {
            let error_text = response.text().await?;
            return Err(anyhow!("API请求失败: {} - {}", response.status(), error_text));
        }

        // 解析响应
        let huawei_response: HuaweiCloudResponse<T> = response.json().await?;

        if huawei_response.code != 0 {
            return Err(anyhow!("华为云API错误: {} - {}",
                huawei_response.code, huawei_response.message));
        }

        huawei_response.data
            .ok_or_else(|| anyhow!("响应数据为空"))
    }

    /// 获取设备列表
    async fn get_devices(&self) -> AnyhowResult<Vec<DeviceInfo>> {
        let url = self.build_api_url("/devices");

        let devices: Vec<DeviceInfo> = self.execute_request(
            reqwest::Method::GET,
            &url,
            None,
        ).await?;

        // 缓存设备信息
        for device in &devices {
            self.cache.cache_device(device.clone()).await;
        }

        Ok(devices)
    }

    /// 获取产品列表
    async fn get_products(&self) -> AnyhowResult<Vec<ProductInfo>> {
        let url = self.build_api_url("/products");

        let products: Vec<ProductInfo> = self.execute_request(
            reqwest::Method::GET,
            &url,
            None,
        ).await?;

        // 缓存产品信息
        for product in &products {
            self.cache.cache_product(product.clone()).await;
        }

        Ok(products)
    }

    /// 转换华为云设备信息为数据源模式
    async fn convert_to_schema(&self, devices: &[DeviceInfo]) -> AnyhowResult<DataSourceSchema> {
        let mut fields = Vec::new();
        let mut relationships = Vec::new();
        let mut constraints = Vec::new();

        // 基础设备字段
        fields.push(FieldDefinition {
            name: "device_id".to_string(),
            data_type: "String".to_string(),
            is_primary_key: true,
            is_nullable: false,
            description: Some("设备唯一标识".to_string()),
            constraints: vec!["max_length(64)".to_string()],
        });

        fields.push(FieldDefinition {
            name: "device_name".to_string(),
            data_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
            description: Some("设备名称".to_string()),
            constraints: vec!["max_length(128)".to_string()],
        });

        fields.push(FieldDefinition {
            name: "product_id".to_string(),
            data_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
            description: Some("产品ID".to_string()),
            constraints: vec!["max_length(64)".to_string()],
        });

        fields.push(FieldDefinition {
            name: "node_type".to_string(),
            data_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
            description: Some("节点类型 (直连设备/边缘节点)".to_string()),
            constraints: vec!["enum(DIRECT, GATEWAY)".to_string()],
        });

        fields.push(FieldDefinition {
            name: "status".to_string(),
            data_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
            description: Some("设备状态".to_string()),
            constraints: vec!["enum(ONLINE, OFFLINE, INACTIVE, FROZEN)".to_string()],
        });

        // 时间字段
        fields.push(FieldDefinition {
            name: "created_time".to_string(),
            data_type: "DateTime".to_string(),
            is_primary_key: false,
            is_nullable: false,
            description: Some("设备创建时间".to_string()),
            constraints: vec![],
        });

        fields.push(FieldDefinition {
            name: "last_online_time".to_string(),
            data_type: "DateTime".to_string(),
            is_primary_key: false,
            is_nullable: true,
            description: Some("最后在线时间".to_string()),
            constraints: vec![],
        });

        // 添加设备到产品的关系
        relationships.push(Relationship {
            source_field: "product_id".to_string(),
            target_entity: "products".to_string(),
            target_field: "product_id".to_string(),
            relationship_type: "belongs_to".to_string(),
            cardinality: "many_to_one".to_string(),
        });

        // 添加状态约束
        constraints.push(Constraint {
            name: "valid_status".to_string(),
            constraint_type: "enum".to_string(),
            field: "status".to_string(),
            value: serde_json::json!(["ONLINE", "OFFLINE", "INACTIVE", "FROZEN"]),
            description: Some("设备状态必须是有效值".to_string()),
        });

        Ok(DataSourceSchema {
            data_source_id: format!("huawei_cloud_{}", self.config.project_id),
            data_source_type: DataSourceType::HuaweiCloud,
            schema_version: "1.0".to_string(),
            fields,
            relationships,
            constraints,
            metadata: {
                let mut metadata = HashMap::new();
                metadata.insert("platform".to_string(), serde_json::Value::String("华为云IoTDA".to_string()));
                metadata.insert("project_id".to_string(), serde_json::Value::String(self.config.project_id.clone()));
                metadata.insert("extracted_at".to_string(), serde_json::Value::String(chrono::Utc::now().to_rfc3339()));
                metadata.insert("device_count".to_string(), serde_json::Value::Number(serde_json::Number::from(devices.len())));
                metadata
            },
        })
    }
}

#[async_trait]
impl DataSourceAdapter for HuaweiCloudAdapter {
    async fn connect(&self) -> AnyhowResult<DataSourceConnection> {
        info!("连接华为云IoTDA平台: project_id={}", self.config.project_id);

        // 测试连接
        let test_url = self.build_api_url("/projects");

        match self.execute_request::<serde_json::Value>(
            reqwest::Method::GET,
            &test_url,
            None,
        ).await {
            Ok(_) => {
                *self.connection_status.write().await = ConnectionStatus::Connected;
                info!("华为云IoTDA连接成功");

                Ok(DataSourceConnection {
                    connection_id: format!("huawei_cloud_{}", uuid::Uuid::new_v4()),
                    data_source_type: DataSourceType::HuaweiCloud,
                    status: ConnectionStatus::Connected,
                    connection_string: self.config.base_url.clone(),
                    created_at: chrono::Utc::now(),
                    last_activity: chrono::Utc::now(),
                    metadata: {
                        let mut metadata = HashMap::new();
                        metadata.insert("project_id".to_string(), self.config.project_id.clone());
                        metadata.insert("base_url".to_string(), self.config.base_url.clone());
                        metadata
                    },
                })
            },
            Err(e) => {
                *self.connection_status.write().await = ConnectionStatus::Error(e.to_string());
                error!("华为云IoTDA连接失败: {}", e);
                Err(e)
            }
        }
    }

    async fn disconnect(&self) -> AnyhowResult<()> {
        info!("断开华为云IoTDA连接");
        *self.connection_status.write().await = ConnectionStatus::Disconnected;
        Ok(())
    }

    async fn test_connection(&self) -> AnyhowResult<TestResult> {
        let start_time = Instant::now();

        match self.connect().await {
            Ok(_) => {
                self.disconnect().await?;
                let duration = start_time.elapsed();

                Ok(TestResult {
                    success: true,
                    message: "华为云IoTDA连接测试成功".to_string(),
                    response_time_ms: duration.as_millis() as u64,
                    details: Some({
                        let mut details = HashMap::new();
                        details.insert("project_id".to_string(), self.config.project_id.clone());
                        details.insert("base_url".to_string(), self.config.base_url.clone());
                        details
                    }),
                })
            },
            Err(e) => {
                let duration = start_time.elapsed();

                Ok(TestResult {
                    success: false,
                    message: format!("华为云IoTDA连接测试失败: {}", e),
                    response_time_ms: duration.as_millis() as u64,
                    details: None,
                })
            }
        }
    }

    async fn extract_schema(&self) -> AnyhowResult<SchemaExtractionResult> {
        info!("提取华为云IoTDA数据模式");

        let start_time = Instant::now();

        // 获取设备和产品信息
        let devices = self.get_devices().await?;
        let products = self.get_products().await?;

        // 转换为数据源模式
        let schema = self.convert_to_schema(&devices).await?;

        // 收集统计信息
        let mut statistics = HashMap::new();
        statistics.insert("device_count".to_string(), serde_json::Value::Number(serde_json::Number::from(devices.len())));
        statistics.insert("product_count".to_string(), serde_json::Value::Number(serde_json::Number::from(products.len())));
        statistics.insert("field_count".to_string(), serde_json::Value::Number(serde_json::Number::from(schema.fields.len())));
        statistics.insert("relationship_count".to_string(), serde_json::Value::Number(serde_json::Number::from(schema.relationships.len())));

        // 按状态统计设备
        let mut status_counts = HashMap::new();
        for device in &devices {
            let count = status_counts.entry(device.status.clone()).or_insert(0);
            *count += 1;
        }
        statistics.insert("device_status_distribution".to_string(), serde_json::to_value(&status_counts)?);

        // 按产品统计设备
        let mut product_counts = HashMap::new();
        for device in &devices {
            let count = product_counts.entry(device.product_id.clone()).or_insert(0);
            *count += 1;
        }
        statistics.insert("device_product_distribution".to_string(), serde_json::to_value(&product_counts)?);

        let extraction_time = start_time.elapsed();

        info!("模式提取完成: 耗时={:?}ms, 设备数量={}, 产品数量={}",
              extraction_time.as_millis(), devices.len(), products.len());

        Ok(SchemaExtractionResult {
            schema,
            extraction_time,
            source_statistics: statistics,
            metadata: {
                let mut metadata = HashMap::new();
                metadata.insert("extraction_method".to_string(), serde_json::Value::String("api_extraction".to_string()));
                metadata.insert("api_version".to_string(), serde_json::Value::String("v5".to_string()));
                metadata.insert("extracted_at".to_string(), serde_json::Value::String(chrono::Utc::now().to_rfc3339()));
                metadata
            },
        })
    }

    async fn query_data(&self, query: &DataQuery) -> AnyhowResult<QueryResult> {
        info!("执行华为云IoTDA数据查询: query_type={:?}", query.query_type);

        let start_time = Instant::now();
        let mut results = Vec::new();

        match query.query_type.as_str() {
            "devices" => {
                let devices = self.get_devices().await?;
                for device in devices {
                    // 应用过滤条件
                    if self.matches_query_conditions(&device, &query.conditions) {
                        let mut record = HashMap::new();
                        record.insert("device_id".to_string(), serde_json::Value::String(device.device_id));
                        record.insert("device_name".to_string(), serde_json::Value::String(device.device_name));
                        record.insert("product_id".to_string(), serde_json::Value::String(device.product_id));
                        record.insert("node_type".to_string(), serde_json::Value::String(device.node_type));
                        record.insert("status".to_string(), serde_json::Value::String(device.status));
                        record.insert("created_time".to_string(), serde_json::Value::String(device.created_time));
                        record.insert("last_online_time".to_string(), serde_json::Value::String(device.last_online_time));

                        if let Some(tags) = device.tags {
                            let tags_json = serde_json::to_value(&tags)?;
                            record.insert("tags".to_string(), tags_json);
                        }

                        results.push(record);
                    }
                }
            },
            "products" => {
                let products = self.get_products().await?;
                for product in products {
                    if self.matches_product_conditions(&product, &query.conditions) {
                        let mut record = HashMap::new();
                        record.insert("product_id".to_string(), serde_json::Value::String(product.product_id));
                        record.insert("product_name".to_string(), serde_json::Value::String(product.product_name));
                        record.insert("device_type".to_string(), serde_json::Value::String(product.device_type));
                        record.insert("protocol_type".to_string(), serde_json::Value::String(product.protocol_type));
                        record.insert("data_format".to_string(), serde_json::Value::String(product.data_format));
                        record.insert("created_time".to_string(), serde_json::Value::String(product.created_time));
                        results.push(record);
                    }
                }
            },
            _ => {
                return Err(anyhow!("不支持的查询类型: {}", query.query_type));
            }
        }

        // 应用分页
        let total_count = results.len();
        if let (Some(offset), Some(limit)) = (query.offset, query.limit) {
            let start = offset.min(total_count);
            let end = (start + limit).min(total_count);
            results = results[start..end].to_vec();
        }

        let query_time = start_time.elapsed();

        info!("查询完成: 耗时={:?}ms, 结果数量={}", query_time.as_millis(), results.len());

        Ok(QueryResult {
            data: results,
            total_count: total_count as u64,
            query_time,
            metadata: {
                let mut metadata = HashMap::new();
                metadata.insert("query_type".to_string(), serde_json::Value::String(query.query_type.clone()));
                metadata.insert("data_source".to_string(), serde_json::Value::String("huawei_cloud".to_string()));
                metadata
            },
        })
    }

    async fn get_connection_status(&self) -> AnyhowResult<ConnectionStatus> {
        Ok(self.connection_status.read().await.clone())
    }

    async fn get_adapter_info(&self) -> AnyhowResult<HashMap<String, serde_json::Value>> {
        let mut info = HashMap::new();
        info.insert("adapter_type".to_string(), serde_json::Value::String("HuaweiCloud".to_string()));
        info.insert("platform".to_string(), serde_json::Value::String("华为云IoTDA".to_string()));
        info.insert("api_version".to_string(), serde_json::Value::String("v5".to_string()));
        info.insert("project_id".to_string(), serde_json::Value::String(self.config.project_id.clone()));
        info.insert("base_url".to_string(), serde_json::Value::String(self.config.base_url.clone()));
        info.insert("supports_caching".to_string(), serde_json::Value::Bool(true));
        info.insert("supports_rate_limiting".to_string(), serde_json::Value::Bool(true));
        Ok(info)
    }
}

impl HuaweiCloudAdapter {
    /// 检查设备是否匹配查询条件
    fn matches_query_conditions(&self, device: &DeviceInfo, conditions: &HashMap<String, serde_json::Value>) -> bool {
        for (key, value) in conditions {
            match key.as_str() {
                "device_id" => {
                    if let Some(expected) = value.as_str() {
                        if device.device_id != expected {
                            return false;
                        }
                    }
                },
                "product_id" => {
                    if let Some(expected) = value.as_str() {
                        if device.product_id != expected {
                            return false;
                        }
                    }
                },
                "status" => {
                    if let Some(expected) = value.as_str() {
                        if device.status != expected {
                            return false;
                        }
                    }
                },
                "node_type" => {
                    if let Some(expected) = value.as_str() {
                        if device.node_type != expected {
                            return false;
                        }
                    }
                },
                _ => {
                    warn!("未知的查询条件: {}", key);
                }
            }
        }
        true
    }

    /// 检查产品是否匹配查询条件
    fn matches_product_conditions(&self, product: &ProductInfo, conditions: &HashMap<String, serde_json::Value>) -> bool {
        for (key, value) in conditions {
            match key.as_str() {
                "product_id" => {
                    if let Some(expected) = value.as_str() {
                        if product.product_id != expected {
                            return false;
                        }
                    }
                },
                "device_type" => {
                    if let Some(expected) = value.as_str() {
                        if product.device_type != expected {
                            return false;
                        }
                    }
                },
                "protocol_type" => {
                    if let Some(expected) = value.as_str() {
                        if product.protocol_type != expected {
                            return false;
                        }
                    }
                },
                _ => {
                    warn!("未知的查询条件: {}", key);
                }
            }
        }
        true
    }
}

impl HuaweiCloudCache {
    pub fn new() -> Self {
        Self {
            device_cache: tokio::sync::RwLock::new(HashMap::new()),
            product_cache: tokio::sync::RwLock::new(HashMap::new()),
            cache_ttl: Duration::from_secs(300), // 5分钟缓存
        }
    }

    pub async fn cache_device(&self, device: DeviceInfo) {
        let mut cache = self.device_cache.write().await;
        let cached_info = CachedDeviceInfo {
            device_info: device,
            cached_at: Instant::now(),
            expires_at: Instant::now() + self.cache_ttl,
        };
        cache.insert(cached_info.device_info.device_id.clone(), cached_info);
    }

    pub async fn get_cached_device(&self, device_id: &str) -> Option<DeviceInfo> {
        let cache = self.device_cache.read().await;
        cache.get(device_id)
            .filter(|cached| cached.expires_at > Instant::now())
            .map(|cached| cached.device_info.clone())
    }

    pub async fn cache_product(&self, product: ProductInfo) {
        let mut cache = self.product_cache.write().await;
        let cached_info = CachedProductInfo {
            product_info: product,
            cached_at: Instant::now(),
            expires_at: Instant::now() + self.cache_ttl,
        };
        cache.insert(cached_info.product_info.product_id.clone(), cached_info);
    }

    pub async fn get_cached_product(&self, product_id: &str) -> Option<ProductInfo> {
        let cache = self.product_cache.read().await;
        cache.get(product_id)
            .filter(|cached| cached.expires_at > Instant::now())
            .map(|cached| cached.product_info.clone())
    }
}

impl RateLimiter {
    pub fn new() -> Self {
        Self {
            request_count: tokio::sync::RwLock::new(0),
            window_start: tokio::sync::RwLock::new(Instant::now()),
            max_requests: 100, // 华为云API通常限制为100请求/分钟
            time_window: Duration::from_secs(60),
        }
    }

    pub async fn acquire(&self) -> AnyhowResult<()> {
        loop {
            let mut count = self.request_count.write().await;
            let mut start = self.window_start.write().await;

            // 如果时间窗口已过期，重置计数器
            if *start + self.time_window <= Instant::now() {
                *count = 0;
                *start = Instant::now();
            }

            // 检查是否超过限制
            if *count < self.max_requests {
                *count += 1;
                return Ok(());
            }

            // 计算等待时间
            let wait_time = (*start + self.time_window) - Instant::now();
            drop(count);
            drop(start);

            debug!("API限流等待: {}ms", wait_time.as_millis());
            tokio::time::sleep(wait_time).await;
        }
    }
}